import 'package:fig/views/home/navigation_home.dart';
import 'package:fig/views/ranking/navigation_ranking.dart';
import 'package:flutter/material.dart';

// 主界面
class BottomNavigationWidget extends StatefulWidget {
  const BottomNavigationWidget({Key key}) : super(key: key); // 参数中的大括号表示可选

  @override
  // _BottomNavigationWidgetState createState() => _BottomNavigationWidgetState();
  _BottomNavigationWidgetState createState() {
    print('生命周期 2. 在[构造函数]后面执行[createState] 只会执行一次');
    return _BottomNavigationWidgetState();
  }
}

class _BottomNavigationWidgetState extends State<BottomNavigationWidget> {
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    print('生命周期 3. 在[createState]后面执行[initState] 只会执行一次');

    // 打开如下示例代码，即可看到 修改 state 后的 组件生命周期
    // Future.delayed(new Duration(seconds: 6), () {
    //   setState(() {
    //     print('BottomNavigationWidget initState setState(_currentIndex = 1)');
    //     _currentIndex = 1;
    //   });
    // });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print('生命周期 4. 在[initState]后面执行[didChangeDependencies]');
  }

  @override
  void didUpdateWidget(BottomNavigationWidget widget) {
    super.didUpdateWidget(widget);
    print('生命周期 -- 当[state]的值被修改的话，会执行这个函数');
  }

  @override
  Widget build(BuildContext context) {
    print('生命周期 -- 在[didUpdateWidget]或[didChangeDependencies]之后执行。因为会执行多次，所以这里不能写业务相关的代码');
    final colorScheme = Theme.of(context).colorScheme;
    final textTheme = Theme.of(context).textTheme;

    // 主显示区域
    var pages = [
      HomeScreen(),
      RankingScreen(),
    ];

    // 导航菜单
    var bottomNavigationBarItems = <BottomNavigationBarItem>[
      BottomNavigationBarItem(icon: const Icon(Icons.home), title: Text("首页")),
      BottomNavigationBarItem(icon: const Icon(Icons.equalizer), title: Text("排行榜")),
    ];

    return Scaffold(
      // body: pages[_currentIndex],
      body: IndexedStack(
        index: _currentIndex,
        children: pages,
      ),
      bottomNavigationBar: BottomNavigationBar(
        showUnselectedLabels: true,
        items: bottomNavigationBarItems,
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        selectedFontSize: textTheme.caption.fontSize,
        unselectedFontSize: textTheme.caption.fontSize,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        selectedItemColor: colorScheme.onPrimary,
        unselectedItemColor: colorScheme.onPrimary.withOpacity(0.38),
        backgroundColor: colorScheme.primary,
      ),
    );
  }
}
